package com.xyz.clientapp;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,
        BluetoothAdapter.LeScanCallback, View.OnKeyListener {

    public static final UUID UUID_SERVICE = UUID.fromString("10000000-0000-0000-0000-000000000000");
    public static final UUID UUID_CHAR_WRITE = UUID.fromString("12000000-0000-0000-0000-000000000000");
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                            int newState) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                System.out.println("========================设备连接成功");
                gatt.discoverServices();
            }
            if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                System.out.println("========================设备连接断开");
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            System.out.println("========================设备可以进行操作");
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic, int status) {

            super.onCharacteristicWrite(gatt, characteristic, status);

        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {


        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                                      BluetoothGattDescriptor descriptor, int status) {

        }
    };
    private BluetoothGatt bluetoothGatt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn).setOnClickListener(this);
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
        findViewById(R.id.btn3).setOnClickListener(this);
        findViewById(R.id.btn4).setOnClickListener(this);
        findViewById(R.id.btn5).setOnClickListener(this);
        findViewById(R.id.btn6).setOnClickListener(this);
        findViewById(R.id.btn7).setOnClickListener(this);
        findViewById(R.id.btn8).setOnClickListener(this);
        findViewById(R.id.btn9).setOnClickListener(this);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    @Override
    public void onClick(View v) {
        if (R.id.btn == v.getId()) {
            startPair();
            return;
        }
        String keyCode = null;
        switch (v.getId()) {
            case R.id.btn1:
                keyCode = "20";
                break;
            case R.id.btn2:
                keyCode = "19";
                break;
            case R.id.btn3:
                keyCode = "21";
                break;
            case R.id.btn4:
                keyCode = "22";
                break;
            case R.id.btn5:
                keyCode = "23";
                break;
            case R.id.btn6:
                keyCode = "4";
                break;
            case R.id.btn7:
                keyCode = "24";
                break;
            case R.id.btn8:
                keyCode = "25";
                break;
            case R.id.btn9:
                keyCode = "3";
                break;
            default:
                break;
        }

        if (!TextUtils.isEmpty(keyCode)) {
            writeData(keyCode);
        }
    }

    private void startPair() {
        //判断蓝牙是否打开
        if (null == mBluetoothAdapter || !mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivityForResult(intent, 10);
            return;
        }
        mBluetoothAdapter.startLeScan(this);
    }

    private void writeData(String keyCode) {
        BluetoothGattService service = bluetoothGatt.getService(UUID_SERVICE);
        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID_CHAR_WRITE);
        characteristic.setValue(keyCode);
        bluetoothGatt.writeCharacteristic(characteristic);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            Toast.makeText(getApplicationContext(), RESULT_OK == resultCode ? "蓝牙开启" : "没有蓝牙", Toast.LENGTH_SHORT).show();
            startPair();
        }
    }

    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        System.out.println("蓝牙设备=========" + device.getName());

        if ("89065746".equals(device.getName())) {
            mBluetoothAdapter.stopLeScan(this);
            bluetoothGatt = device.connectGatt(getApplicationContext(), false, gattCallback);
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        System.out.println("keycode=================================" + keyCode);
        return false;
    }

}
